// 节流函数，限制事件触发频率
function throttle(fn, delay) {
    let lastCall = 0;
    return function(...args) {
        const now = new Date().getTime();
        if (now - lastCall < delay) return;
        lastCall = now;
        return fn.apply(this, args);
    };
}

// 优化窗口大小调整函数
function adjustFeatureHeights() {
    const windowWidth = window.innerWidth;
    const isMobile = windowWidth < 768;
    const scaleFactor = isMobile ? (768 - windowWidth) / 768 + 1 : 1;
    
    const features = ['mi', 'ai', 'bi', 'ee'];
    const heights = {};
    
    // 先获取所有高度，减少DOM操作
    features.forEach(feature => {
        const element = $(`.feature-${feature}`);
        heights[feature] = {
            height: element.height(),
            paddingTop: parseInt(element.css("padding-top")) || 0
        };
    });
    
    // 检查是否需要调整
    const shouldAdjust = isMobile || 
        (heights.mi.height < 641 || heights.ai.height < 641 || heights.bi.height < 641);
    
    if (!shouldAdjust) {
        // 移除所有样式
        features.forEach(feature => {
            $(`.${feature}-headline-bg`).removeAttr("style");
        });
        return;
    }
    
    // 应用调整
    features.forEach(feature => {
        const element = $(`.${feature}-headline-bg`);
        const extraHeight = feature === 'ee' ? 20 * scaleFactor : 28 * scaleFactor;
        const totalHeight = heights[feature].height + extraHeight + 
                          (feature === 'ee' ? heights[feature].paddingTop : 0);
        element.css("height", totalHeight + "px");
    });
}

// 优化后的SineWaves管理类
class WaveManager {
    constructor() {
        this.instances = [];
        this.throttledHandlers = [];
    }
    
    createInstance(id, options) {
        const element = $(`#${id}`);
        const parent = element.parent();
        
        const config = {
            el: document.getElementById(id),
            speed: options.speed,
            width: () => {
                return window.innerWidth < 768 
                    ? options.smallWidthFactor * parent.width() 
                    : options.largeWidthFactor * parent.width();
            },
            height: () => parent.height(),
            wavesWidth: "100%",
            ease: "SineInOut",
            waves: options.waves,
            initialize: function() {},
            resizeEvent: function() {
                const gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
                gradient.addColorStop(0, "rgba(255, 255, 255, 0)");
                gradient.addColorStop(0.5, options.gradientMiddleColor);
                gradient.addColorStop(1, "rgba(255, 255, 255, 0)");
                
                this.waves.forEach(wave => {
                    wave.strokeStyle = gradient;
                });
            }
        };
        
        const instance = new SineWaves(config);
        this.instances.push(instance);
        
        // 添加可见性检查
        const handler = throttle(() => this.checkVisibility(instance, element), 100);
        this.throttledHandlers.push(handler);
        
        // 初始检查和事件绑定
        handler();
        window.addEventListener('resize', handler);
        window.addEventListener('scroll', handler);
        
        return instance;
    }
    
    checkVisibility(instance, element) {
        const rect = element[0].getBoundingClientRect();
        const windowHeight = window.innerHeight;
        const isVisible = rect.top < windowHeight && rect.bottom > 0;
        
        if (instance.running !== isVisible) {
            instance.running = isVisible;
            if (isVisible) {
                instance.update();
            }
        }
    }
    
    cleanup() {
        this.throttledHandlers.forEach(handler => {
            window.removeEventListener('resize', handler);
            window.removeEventListener('scroll', handler);
        });
        this.instances = [];
        this.throttledHandlers = [];
    }
}

// 主函数
$(document).ready(function() {
    // 初始化高度调整
    const throttledAdjust = throttle(adjustFeatureHeights, 100);
    setTimeout(throttledAdjust, 100);
    window.addEventListener('resize', throttledAdjust);
    
    // 初始化波浪动画
    const waveManager = new WaveManager();
    
    // 创建波浪实例
    waveManager.createInstance('waves', {
        speed: 4,
        smallWidthFactor: 2,
        largeWidthFactor: 1.2,
        gradientMiddleColor: "rgba(255, 255, 255, 0.1)",
        waves: Array.from({length: 20}, (_, i) => ({
            timeModifier: 0.5,
            lineWidth: 2,
            amplitude: (20 - i) * 8,
            wavelength: ((20 - i) * 8) + 50,
            segmentLength: 1
        }))
    });
    
    waveManager.createInstance('waves21', {
        speed: 8,
        smallWidthFactor: 3,
        largeWidthFactor: 1.4,
        gradientMiddleColor: "rgba(255, 255, 255, 0.2)",
        waves: [
            {
                timeModifier: 0.5,
                lineWidth: 2,
                amplitude: 160,
                wavelength: 150,
                segmentLength: 1
            },
            {
                timeModifier: 0.6,
                lineWidth: 2,
                amplitude: 100,
                wavelength: 100,
                segmentLength: 1
            }
        ]
    });
    
    waveManager.createInstance('waves2', {
        speed: 8,
        smallWidthFactor: 3,
        largeWidthFactor: 1.4,
        gradientMiddleColor: "rgba(255, 255, 255, 0.2)",
        waves: [
            {
                timeModifier: 0.5,
                lineWidth: 2,
                amplitude: 100,
                wavelength: 150,
                segmentLength: 1
            },
            {
                timeModifier: 0.5,
                lineWidth: 2,
                amplitude: 50,
                wavelength: 80,
                segmentLength: 1
            }
        ]
    });
    
    // 页面卸载时清理
    $(window).on('unload', function() {
        waveManager.cleanup();
    });
});